package com.ruoyi.device.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.device.domain.DeviceAlarmHistory;
import com.ruoyi.device.domain.req.alarm.AlarmHistoryAddReq;
import com.ruoyi.device.domain.req.alarm.AlarmHistoryEditReq;
import com.ruoyi.device.domain.req.alarm.AlarmHistoryReq;
import com.ruoyi.device.service.DeviceAlarmHistoryService;
import com.ruoyi.device.mapper.DeviceAlarmHistoryMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author 11452
* @description 针对表【device_alarm_history(设备报警历史表)】的数据库操作Service实现
* @createDate 2023-12-07 14:16:31
*/
@Service
public class DeviceAlarmHistoryServiceImpl extends ServiceImpl<DeviceAlarmHistoryMapper, DeviceAlarmHistory>
    implements DeviceAlarmHistoryService{

    /**
     * 设备报警历史记录查询
     * @param req
     * @return
     */
    @Override
    public List<DeviceAlarmHistory> search(AlarmHistoryReq req) {
        LambdaQueryWrapper<DeviceAlarmHistory> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceAlarmHistory::getDeviceId,req.getDeviceId());
        //处理标识
        if(StrUtil.isNotBlank(req.getHandlesFlag())){
            queryWrapper.eq(DeviceAlarmHistory::getHandlesFlag,req.getHandlesFlag());
        }
        queryWrapper.orderByDesc(DeviceAlarmHistory::getAlarmTime);
        return this.list(queryWrapper);
    }

    /**
     * 新增报警记录
     * @param req
     * @return
     */
    @Override
    public Boolean add(AlarmHistoryAddReq req) {
        DeviceAlarmHistory  entity=new DeviceAlarmHistory();
        BeanUtils.copyProperties(req,entity);
        //未处理
        entity.setHandlesFlag("0");
        return this.save(entity);
    }

    /**
     * 报警处理
     * @param req
     * @return
     */
    @Override
    public Boolean edit(AlarmHistoryEditReq req) {
        DeviceAlarmHistory db=this.baseMapper.searchNoHandlerHistory(req);
        if(Objects.isNull(db)){
            throw new ServiceException("查询不到数据");
        }

        DeviceAlarmHistory entity=new DeviceAlarmHistory();
        entity.setId(db.getId());
        entity.setHandlesDate(new Date());
        entity.setHandlesFlag("1");
        entity.setHandlesUser(SecurityUtils.getUsername());
        entity.setRemark(req.getRemark());
        return this.updateById(entity);
    }
}




